<template>
    <div class="card-container" style="padding-right: 25px;">

        <el-form ref="categoryForm" :model="categoryForm" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="大类Id:" prop="id" style="font-weight: 600">
                <span>{{ categoryForm.id }}</span>
            </el-form-item>
            <el-form-item label="名称:" prop="name">
                <el-input v-model="categoryForm.name" />
            </el-form-item>
            <el-form-item label="状态:" prop="status">
                <el-select v-model="categoryForm.status" placeholder="请选择大类状态">
                    <el-option label="显示" :value="1" />
                    <el-option label="隐藏" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属父类:" prop="affiliate">
                <el-cascader
                    v-model="categoryForm.affiliate"
                    :options="cascadeOptions"
                    :props="{ expandTrigger: 'hover',checkStrictly: true, label: 'name', value: 'id'}"
                    placeholder="当前大类为根节点"
                />
            </el-form-item>
            <el-form-item>
                <el-tooltip slot="label" content="若大类下无文章 可插入子大类节点" placement="left">
                    <span>有无文章:</span>
                </el-tooltip>
                <template v-if="categoryForm.isLeaf">
                    <el-col :span="2">
                        <span style="font-weight: 600">有</span>
                    </el-col>
                    <el-col :span="9" :offset="1">
                        <el-link type="primary" :underline="false" @click="toPostList(categoryForm.id)">
                            查看文章列表<i class="el-icon-view el-icon--right" />
                        </el-link>
                    </el-col>
                </template>
                <span v-else style="font-weight: 600">无</span>
            </el-form-item>
            <el-form-item label="创建时间:">
                <span>{{ categoryForm.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间:">
                <span>{{ categoryForm.updateTime }}</span>
            </el-form-item>

            <el-form-item style="margin-bottom: 50px">
                <el-button type="primary" @click="submitCategoryForm">保存</el-button>
                <el-button @click="resetCategoryForm">重置</el-button>
            </el-form-item>
            <el-divider content-position="left">重要操作</el-divider>
            <el-form-item v-if="!categoryForm.isLeaf" label="在当前大类下新增类别:" style="text-align: right" label-width="175px">
                <el-button type="success" @click="handleCreate">添加附属大类</el-button>
            </el-form-item>
            <el-form-item label="删除该大类及其附属子类/文章:" style="text-align: right" label-width="220px">
                <el-button type="danger" @click="handleDelete">删除当前大类</el-button>
            </el-form-item>
        </el-form>

        <el-dialog title="新增大类" :visible.sync="dialogFormVisible" :modal-append-to-body="false" width="600px">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="140px" style="width: 350px; margin-left:50px;">
                <el-form-item label="名称" prop="name">
                    <el-input ref="tempName" v-model="temp.name" />
                </el-form-item>
                <el-form-item label="状态:" prop="categoryStatus">
                    <el-select v-model="temp.categoryStatus" placeholder="请选择大类状态">
                        <el-option label="显示" :value="1" />
                        <el-option label="隐藏" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属父类:">
                    <template v-if="!isRoot">
                        <el-tag effect="plain">{{ categoryForm.name }}</el-tag>
                        <el-tag type="info" style="margin-left: 12px">ID: {{ categoryForm.id }}</el-tag>
                    </template>
                    <template v-else>
                        <el-tag type="warning">软件学院</el-tag>
                        <el-tag type="info" style="margin-left: 12px">ID: 0</el-tag>
                    </template>
                </el-form-item>
                <el-form-item>
                    <el-tooltip slot="label" content="Bottom center" placement="left">
                        <span>是否设置为根节点:</span>
                    </el-tooltip>
                    <el-switch
                        v-model="isRoot"
                        active-color="#13ce66"
                    />
                    <span v-if="isRoot" style="padding-left: 10px; font-size: 12px">
                        注: 默认不绑定至导航条
                    </span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="createData()">
                    确认创建
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { createCategory, deleteCategory, getCategoryDetail, updateCategory } from '@/api/category'

export default {
    name: 'CategoryForm',
    props: {
        cascadeOptions: {
            type: Array,
            default: () => []
        },
        affiliateList: {
            type: Array,
            default: () => []
        },
        categoryProps: {
            type: Object,
            default: () => {
                return {
                    id: 0,
                    name: '无',
                    isLeaf: false,
                    status: 1
                }
            }
        }
    },
    data() {
        return {
            categoryForm: {
                id: 0,
                name: '',
                isLeaf: false,
                status: undefined,
                affiliate: [],
                parentId: -1,
                hasParentChange: false, // 判断父节点是否发生改变
                createTime: '',
                updateTime: ''
            },

            // 新增大类表单
            dialogFormVisible: false,
            isRoot: false,
            temp: {
                name: '',
                categoryStatus: 0,
                parentId: 0
            },

            // 表单验证规则
            rules: {
                name: [
                    { required: true, message: '请输入大类名称' }
                ],
                categoryStatus: [
                    { required: true, message: '请选择大类状态', trigger: 'change' }
                ]
            }
        }
    },
    watch: {
        'categoryProps.id': {
            handler: function() {
                const _props = this.categoryProps
                this.categoryForm = {
                    affiliate: this.affiliateList,
                    id: _props.id,
                    name: _props.name,
                    isLeaf: _props.isLeaf,
                    status: _props.status,
                    createTime: '',
                    updateTime: ''
                }
                const _form = this.categoryForm
                getCategoryDetail(_props.id).then(data => {
                    _form.createTime = data.createTime
                    _form.updateTime = data.updateTime
                    _form.parentId = data.parentId
                    if (_props.name !== data.name ||
                        _props.status !== data.categoryStatus ||
                        (this.affiliateList.length > 0 &&
                            this.affiliateList[this.affiliateList.length - 1] !== data.parentId)
                    ) {
                        // this.$message.error('大类树信息不符,需要刷新')
                        this.$emit('tree-refresh')
                    }
                })
            }
        }
    },
    methods: {
        submitCategoryForm() {
            this.$refs['categoryForm'].validate((valid) => {
                if (valid) {
                    // 判断所属大类是否发生变化
                    const _affiliate = this.categoryForm.affiliate
                    if ((_affiliate.length === 0 && this.affiliateList.length === 0) ||
                        _affiliate[_affiliate.length - 1] === this.affiliateList[this.affiliateList.length - 1]) {
                        this.categoryForm.hasParentChange = false
                    } else {
                        this.categoryForm.hasParentChange = true
                    }
                    // 待上传的parentId
                    const _parentId = this.categoryForm.hasParentChange && _affiliate.length > 0
                        ? _affiliate[_affiliate.length - 1] : this.categoryForm.parentId
                    // 上传数据
                    const _data = {
                        categoryStatus: this.categoryForm.status,
                        name: this.categoryForm.name,
                        parentId: _parentId
                    }
                    updateCategory(this.categoryForm.id, _data).then(() => {
                        this.$message.success('大类更新成功!')
                        this.$emit('card-submit', this.categoryForm)

                        // 如果所属大类层级, 且原本为1级大类
                        if (this.categoryForm.hasParentChange && this.affiliateList.length === 0) {
                            this.$notify({
                                title: '警告',
                                type: 'warning',
                                dangerouslyUseHTMLString: true,
                                message: '大类: <strong>' + this.categoryForm.name + ' ' + this.categoryForm.id +
                                        '</strong><br>不再为一级大类 将在<strong>导航栏设置</strong>中隐藏',
                                duration: 10000
                            })
                        }
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        resetCategoryForm() {
            const props = this.categoryProps
            this.categoryForm.name = props.name
            this.categoryForm.status = props.status
            this.categoryForm.affiliate = this.affiliateList
        },

        // 新增大类
        handleCreate() {
            this.resetTemp()
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.$refs['tempName'].focus()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    if (this.isRoot) { // 处理根节点情况
                        this.temp.parentId = 0
                    }
                    // 从后端获取新建大类后对象
                    createCategory(this.temp).then(data => {
                        const _data = {
                            parent_id: data.parentId,
                            node_data: {
                                id: data.id,
                                name: data.name,
                                status: data.categoryStatus
                            }
                        }
                        this.$emit('node-create', _data)
                        this.dialogFormVisible = false
                    })
                }
            })
        },
        resetTemp() {
            this.isRoot = false
            this.temp = {
                name: '',
                categoryStatus: 1,
                parentId: this.categoryForm.id
            }
        },
        handleDelete() {
            this.$confirm('此操作将永久删除大类:\"' + this.categoryProps.name + '\"  ID:' + this.categoryProps.id + ' ,是否继续? (若存在子类则全部隐藏)', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const _id = this.categoryProps.id
                deleteCategory(_id).then(() => {
                    this.$emit('node-delete', _id)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        /**
         * 跳转至文章列表, 搜索对应cid
         * @param cid 大类id
         */
        toPostList(cid) {
            this.$router.push({ path: '/post/list', query: { cid: cid }})
        }
    }
}
</script>
